# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.log import logger
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website.constant import SUPER_POWER
from website.models import Menu
from website.usercontrol.models import SysRole
from website import  settings
import os,datetime

@csrf_exempt
def default(request):
    return render_to_response('login.html')

@csrf_exempt
def top(request):
    CurrentUser=request.session.get('CurrentUser')
    return render_to_response('top.html',{'CurrentUser':CurrentUser})

@csrf_exempt
def index(request):
    return render_to_response('index.html')


@csrf_exempt
def index_display(request):
    CurrentUser=request.session.get('CurrentUser')
    queryset=CurrentUser.index_record.all()
    return HttpResponse(dumps({'success':'true','data':list(queryset.values('text','portlet'))}))



def main(request):
    CurrentUser=request.session.get('CurrentUser')
    if CurrentUser is None:
        return HttpResponseRedirect('/')    
    return render_to_response('main.html')


@csrf_exempt
def menu(request):
    CurrentUser=request.session.get('CurrentUser')
    if CurrentUser.is_superuser==SUPER_POWER:
        menus=Menu.objects.all()
    else:
        menus=SysRole.objects.get(id=CurrentUser.role.id).role_menu.all()
    
    nodes=to_node(menus)
    for childrenNode in nodes:
        for parentNode in nodes:
            if childrenNode['parent_id'] == parentNode['id']:
                try:
                    parentNode['children'].append(childrenNode)
                except KeyError:
                    parentNode['children']=[]
                    parentNode['children'].append(childrenNode)
    data=[]
    for node in nodes:
        if node['parent_id']==None :
            data.append(node)
    return HttpResponse(dumps({'success':'true','data':data}))

@csrf_exempt
def menu_request(request,model,page):    
    path = '%s/%s.html' % (model,page)
    return render_to_response(path)



@csrf_exempt
def menu_list(request):
    menus=Menu.objects.all()
    nodes=to_node(menus)
    for childrenNode in nodes:
        for parentNode in nodes:
            if childrenNode['parent_id'] == parentNode['id']:
                parentNode['expanded']=True
                try:
                    parentNode['children'].append(childrenNode)
                except KeyError:
                    parentNode['children']=[]
                    parentNode['children'].append(childrenNode)
    data=[]
    for node in nodes:
        if node['parent_id']==None :
            data.append(node)
    return HttpResponse(dumps(data))    


@csrf_exempt
def menu_select(request):
    menus=Menu.objects.all()
    nodes=to_node(menus)
    return HttpResponse(dumps(nodes)) 

def to_node(items):
    nodes=[]
    for item in items:
        node={}
        node['id']=item.id
        node['text']=item.name
        node['leaf']=item.is_leaf
        node['display']=item.is_display
        node['navi']=item.is_navi
        node['url']=item.url
        node['parent_id']=item.parent_id
        nodes.append(node)
    return nodes


@csrf_exempt
def menu_save(request):
    try:
        menu_id=request.POST.get('menu_id','')
        menu_name=request.POST.get('menu_name', '')
        menu_url=request.POST.get('menu_url', '')
        menu_display=request.POST.get('menu_display',0)
        menu_leaf=request.POST.get('menu_leaf',0)
        menu_navi=request.POST.get('menu_navi',0)
        menu_parent_id=request.POST.get('menu_parent_id',None)
        if menu_id =='':
            #新增
            Menu.objects.create(name=menu_name,url=menu_url,is_display=menu_display,
                                is_leaf=menu_leaf,is_navi=menu_navi,parent_id=menu_parent_id)
        else:
            #修改
            menu=Menu.objects.get(id=menu_id)
            menu.name=menu_name
            menu.url=menu_url
            menu.is_display=menu_display
            menu.is_leaf=menu_leaf
            menu.is_navi=menu_navi
            menu.parent_id=menu_parent_id
            menu.save()
    except Exception,ex:
        logger.error(ex)
        return HttpResponse(dumps({'success':False,'message':'失败！'}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def menu_del(request):
    try:
        menu_id=request.POST.get('menu_id','')
        Menu.objects.get(id=menu_id).delete()
    except:
        return HttpResponse(dumps({'success':False,'message':'删除失败！'}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))
        

@csrf_exempt
def uploaded(request):
    f=request.FILES['file']
    try:
        root,ext=os.path.splitext(f.name)
        now=datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
        destination=open(os.path.join(settings.MEDIA_ROOT, now+ext).replace('\\','/'),'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    except:
        return HttpResponse(dumps({'success':False,'message':'上传失败！','filename':f.name}))   
    return HttpResponse(dumps({'success':True,'message':'上传成功！','filename':now+ext}))  

@csrf_exempt
def downloaded(request):
    filepath=request.GET.get('path','')
    filename=request.GET.get('name','')
    try:
        f=open(os.path.join(settings.MEDIA_ROOT, filepath).replace('\\','/'),'rb')
        data=f.read()
        f.close()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)})) 
    response = HttpResponse(data,mimetype='application/octet-stream') 
    response['Content-Encoding'] = 'utf-8'
    response['Content-Disposition'] = 'attachment; filename="%s"' % (filename.encode('utf-8'),)
    return response;

if __name__=="__main__":
    f=open('F:/外包项目/测试服务器地址.txt')
